<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        class="alert-opt"
        :closable="false"
        show-icon
        title="注意：只允许为第三级设置相关参数!"
        type="warning"
      ></el-alert>
      <el-row>
        <el-col>
          <span>
            选择商品分类：
            <!-- 级联选择框 -->
            <el-cascader
              v-model="selectedCateKeys"
              :options="cateList"
              expandTrigger="hover"
              :props="cascaderProps"
              @change="handleChange"
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- tab栏区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="showAddDialog">添加参数</el-button>
          <el-table border :data="manyAttrData" stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="tag"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scopeProps">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scopeProps.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams((scopeProps.row))"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="showAddDialog">添加属性</el-button>
          <el-table border :data="onlyAttrData" stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="tag"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scopeProps">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scopeProps.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams((scopeProps.row))"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      @close="addFormDialogClose"
      :title="'添加' + titleName"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      @close="eidtFormDialogClose"
      :title="'修改' + titleName"
      :visible.sync="eidtDialogVisible"
      width="50%"
    >
      <el-form
        :model="eidtForm"
        :rules="eidtFormRules"
        ref="eidtFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="eidtForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类数据列表
      cateList: [],
      // 选中的分类id
      selectedCateKeys: [],
      // 级联选则框的数据
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 激活的页签的名称
      activeName: 'many',
      // 动态参数的数据
      manyAttrData: [],
      // /静态属性的数据
      onlyAttrData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {},
      addFormRules: {
        attr_name: [
          { required: true, tigger: 'blur', message: '参数名称不能为空' }
        ]
      },
      // 控制修改参数对话框的显示与隐藏
      eidtDialogVisible: false,
      // 将用编辑的参数
      eidtForm: {},
      eidtFormRules: {
        attr_name: [
          { required: true, tigger: 'blur', message: '参数名称不能为空' }
        ]
      }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品数据失败')
      }
      this.cateList = res.data
    },
    // 级联选择框变化时会触发该函数
    handleChange() {
      // console.log(this.getCateId)
      this.getCateAttributes()
    },
    // 获取分类属性
    async getCateAttributes() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyAttrData = []
        this.onlyAttrData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res)
      if (this.activeName === 'many') {
        this.manyAttrData = res.data
      } else {
        this.onlyAttrData = res.data
      }
    },
    // 点击tab按钮切换
    handleTabClick() {
      this.getCateAttributes()
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    addFormDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮添加参数
    async addParams() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
      })
      const { data: res } = await this.$http.post(
        `categories/${this.getCateId}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 201) return this.$message.error('添加参数失败')
      this.$message.success('添加参数成功')
      this.addDialogVisible = false
      this.getCateAttributes()
    },
    // 显示修改参数的对话框
    showEditDialog(props) {
      this.eidtDialogVisible = true
      this.eidtForm = props
    },
    eidtFormDialogClose() {
      this.$refs.eidtFormRef.resetFields()
    },
    // 编辑参数
    eidtParams() {
      this.$refs.eidtFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.getCateId}/attributes/${this.eidtForm.attr_id}`,
          { attr_sel: this.activeName, attr_name: this.eidtForm.attr_name }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('参数修改失败')
        this.$message.success('参数更新成功')
        this.getCateAttributes()
        this.eidtDialogVisible = false
      })
    },
    // 根据ID删除对应的参数项
    delParams(props) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.getCateId}/attributes/${props.attr_id}`
          )
          this.getCateAttributes()
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 失去焦点或按下 Enter键 都会触发
    handleInputConfirm(props) {
      if (props.inputValue.trim().length === 0) {
        props.inputValue = ''
        props.inputVisible = false
        return false
      }
      // 如果没有return 则证明输入的内容，需要做后续处理
      props.attr_vals.push(props.inputValue)
      props.inputValue = ''
      props.inputVisible = false
      this.saveCateData(props)
    },
    async saveCateData(props) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCateId}/attributes/${props.attr_id}`,
        {
          attr_name: props.attr_name,
          attr_sel: this.activeName,
          attr_vals: props.attr_vals.join(',')
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success('更新参数成功')
    },
    // 点击按钮，展示文本输入框
    showInput(props) {
      props.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用， 就是当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击删除参数标签
    handleClose(i, scope) {
      scope.attr_vals.splice(i, 1)
      this.saveCateData(scope)
    }
  },
  computed: {
    isBtnDisable() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    getCateId() {
      return this.selectedCateKeys[this.selectedCateKeys.length - 1]
    },
    titleName() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
.alert-opt {
  margin: 15px 0;
}
.el-cascader {
  width: auto;
}
.tag {
  margin: 5px;
}
.input-new-tag {
  width: 100px;
}
</style>
